package com.sgcc.pda.ssal.service;

import android.content.Context;
import android.content.Intent;
import android.os.RemoteException;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.hzwq.codec.util.ByteTools;
import com.sgcc.pda.baselibrary.ConstPath;
import com.sgcc.pda.baselibrary.thread.FixedThreadUtil;
import com.sgcc.pda.baselibrary.utils.ErrorLogUtil;
import com.sgcc.pda.baselibrary.utils.InputCheckUtil;
import com.sgcc.pda.baselibrary.utils.JsonUtil;
import com.sgcc.pda.baselibrary.utils.LogUtil;
import com.sgcc.pda.baselibrary.utils.UUIDUtil;
import com.sgcc.pda.baselibrary.utils.ZipUtil;
import com.sgcc.pda.hzaidl.entity.CommonErrorBean;
import com.sgcc.pda.hzaidl.error.HZErrorCode;
import com.sgcc.pda.mdrh.app.ZoomApplication;
import com.sgcc.pda.mdrh.zoom.router.BaseOperateRouter;
import com.sgcc.pda.model.web.response.BlockUploadProgress;
import com.sgcc.pda.model.web.response.ErrorMsg;
import com.sgcc.pda.sdk.entity.BaseEntity;
import com.sgcc.pda.sdk.utils.DataConversionUtil;
import com.sgcc.pda.sdk.utils.NetWorkUtil;
import com.sgcc.pda.sdk.utils.ZoomSPUtils;
import com.sgcc.pda.sdk.utils.db.SharepreferenceUtil;
import com.sgcc.pda.ssallib.enums.RequestMethod;
import com.sgcc.pda.ssallib.http.HttpClientUtil2;
import com.sgcc.pda.ssallib.listeners.DownLoadListener;
import com.sgcc.pda.ssallib.model.callback.IDataCallback;
import com.sgcc.pda.web.IHttpCallbackInterface;
import com.sgcc.pda.web.download.FileUtils;
import com.sgcc.pda.web.service.FileWget;
import com.sgcc.pda.web.upload.listener.UploadListener;
import com.sgcc.pda.web.upload.manager.UploadManager;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import web.pda.sgcc.com.websdk.http.BaseRequestParams;
import web.pda.sgcc.com.websdk.http.OkHttpManager;
import web.pda.sgcc.com.websdk.util.FileUtil;
import web.pda.sgcc.com.websdk.util.HttpClientUtil;


/**
 * 网络请求控制类.
 *
 * @author 王沛栋
 * @data 2018/1/22 14:48
 */

public class SsalWebControler {
    private static final String TAG_POST = "postData";
    private static final String TAG_UPFILE = "uploadlogfile";
    private static final int HTTP_RESPONSE_CODE_SUCCESS = 1;//响应成功
    private static final int HTTP_RESPONSE_CODE_DOWNLOADING = 2;//下载中
    private static final int HTTP_RESPONSE_CODE_FAIL = 0;//响应失败
    private static final int HTTP_REQUEST_CODE_CANCEL = -1;//请求取消
    private static final int HTTP_REQUEST_NO_NET_WORK = -2;//无网络连接

    private static final String DOWNLOAD_SERVER = "reqHttpFileDown.do";//reqHttpFileDown

    private static final String INTENT_ID = "INTENT_ID";
    private static final String CODE = "CODE";

    private static final String HTTP_REQUEST_CANCEL = "您取消了服务请求";
    private static final String HTTP_NET_NETWORK = "网络异常！";
    private static final String HTTP_UPLOAD_FILE_FAIL = "文件上传失败！";
    private static final String HTTP_UPLOAD_FILE_SUCCESS = "文件上传成功！";
    private static final String HTTP_URL_ERROR = "您访问的路径不合法！";
    private static final String URL_WRONG = "url非法";
    private static final String TEXT_REQUEST_PARAM = "请求json参数";
    private static final String WEB_SUCCESS = "web请求成功";
    private static final String WEB_FAILED = "web请求失败";
    private static final String DOWN_SUCCESS = "下载成功:";
    private static final String DOWN_FAILED = "下载失败:";

    private static final String SERVER_NAME_E = "SERVER_NAME=";
    private static final String SERVER_NAME = "SERVER_NAME";
    private static final String REQUEST_PARM_E = "&REQUEST_PARM=";
    private static final String REQUEST_PARM = "REQUEST_PARM";
    private static final String UID_E = "&UID=";
    private static final String MAC_E = "&MAC=";
    private static final String UTF8 = "UTF-8";
    private static final String UPFILESERVER = "upfileserver";
    private static final String UPLOADFILES = "uploadfiles";
    private static final String TYPE_PNG = "image/png";
    private static final String FILES = "files";
    private static final String LOG_UPLOAD_FAIL = "上传失败:";


    public static final String REQ_HTTP = "commfront.do";//用户登录  //loginUid.do  getHandsetUsers
    public static final String SERVICE_NAME = "eomfront";//用户登录  //loginUid.do  getHandsetUsers

    public static final String PLS_CHECK_IP_PORT = "请检查IP地址和端口";
    private static final String COMMON_URI_PRE = "/eomfront/FrontSys/";
    private static long UPLOAD_SIZE_LIMIT;


    /**
     * 定义想应用发送广播的名称
     */
    private static final String BROADCAST_PERMISSION_DISC = "com.sgcc.pda.permissions.COMM_BROADCAST";

    public static SsalWebControler mInstance;

    public static SsalWebControler getInstance() {
        synchronized (SsalWebControler.class) {
            if (mInstance == null) {
                mInstance = new SsalWebControler();
            }
            return mInstance;
        }
    }

    /**
     * 获取请求服务的url 因为有可能修改ip和端口 所以这个地方不能以空为判断  所以每次都需要重新请求
     *
     * @param context 上下文
     * @return host
     */
    private String getUrl(Context context) {
        String ip, port;
        if (SharepreferenceUtil.getCommUsbEnable(context)) {
            ip = SharepreferenceUtil.getCommIpUSB(context);
            port = SharepreferenceUtil.getCommPortUSB(context);
        } else {
            ip = SharepreferenceUtil.getCommIp(context);
            port = SharepreferenceUtil.getCommPort(context);
        }
        return "http://" + ip + ":" + port + "/eomfront" + "/FrontSys/";
    }


    /**
     * 公共下载文件方法-使用老的前置下载方式
     *
     * @param context
     * @param methodName 请求uri，
     * @param type       类型  0 不使用进度条 1使用进度条
     * @param fileName
     */
    public void downloadComm(final Context context, String methodName, final int type, final String fileName, String savePath, final BaseOperateRouter.CompleteListener completeListener) {

        if (!SharepreferenceUtil.getCommUsbEnable(context) && !NetWorkUtil.getInstance().isConnected(context)) {
            //无网络时进入主界面
            CommonErrorBean commonErrorBean = new CommonErrorBean(HZErrorCode.ERROR_2001.getCode(), HZErrorCode.ERROR_2001.getErrMessage());
            completeListener.complete(0, new Gson().toJson(commonErrorBean));
            return;
        }

        String ip = getIP(context);
        int port = getPort(context);
        String uri = getUri(methodName);
        String yesam = getYESAM(context);
        String seq = getSeq();


//            String requestParms = functionName + "?FID_NO=" + fileId;

        com.hzwq.codec.client.model.BaseRequestParams params = new com.hzwq.codec.client.model.BaseRequestParams();
//            params.put("SERVER_NAME", serverName);
//            params.put("REQUEST_PARM", DataConversionUtil.str2HexStr(requestParms));
//            params.put("UID", SharepreferenceUtil.getUid(ZoomApplication.getInstance()));
//            params.put("MAC", "12345");
//            params.setRequestMethod(RequestMethod.GET);

        //先创建文件夹
        markDownloadDir();

//                String fName = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        final String fileLocPath = ConstPath.DOWNLOAD_PATH + fileName;

        HttpClientUtil2.download(context, type, fileLocPath, new DownLoadListener() {
            @Override
            public void onProgress(long curr, long total) {
                DecimalFormat format = new DecimalFormat("0");
                String progress = format.format((float) curr / total * 100);

            }

            @Override
            public void onSuccess(String filePath) {

                //发送下载路径
                HashMap<String, String> map = new HashMap<>();
                map.put("RT_F", "1");
                map.put("RT_D", "下载成功");
                map.put("FILE_PATH", fileLocPath);
                String s = JsonUtil.mapToJson(map);
                completeListener.complete(1, s);

            }

            @Override
            public void onFailure(String error) {
                LogUtil.e(DOWN_FAILED + error);
                HashMap<String, String> map = new HashMap<>();
                map.put("RT_F", "0");
                map.put("RT_D", DOWN_FAILED + error);
                String s = JsonUtil.mapToJson(map);
                completeListener.complete(0, s);

                //下载失败删除文件
                File file = new File(fileLocPath);
                if (file.exists()) {
                    FileUtil.deleteFile(file);
                }

            }
        }, ip, port, uri, yesam, seq, params);


    }


    /**
     * 取消网络请求
     *
     * @param context
     * @param broadcastName
     */
    public void cancle(Context context, String broadcastName) {
        LogUtil.e("取消网路请求");
        HttpClientUtil.cancle(context);

        if (!TextUtils.isEmpty(broadcastName)) {
            sendBroadcast(context, broadcastName, HTTP_REQUEST_CANCEL, HTTP_REQUEST_CODE_CANCEL);
        }
    }


    /**
     * 发送广播
     *
     * @param context
     * @param boradcastName
     * @param result
     */
    private void sendBroadcast(Context context, String boradcastName, String result, int code) {
        Intent intent = new Intent();
        intent.setAction(boradcastName);
        intent.putExtra(INTENT_ID, result);
        intent.putExtra(CODE, code);
        context.sendBroadcast(intent, BROADCAST_PERMISSION_DISC);
    }


    private void markDownloadDir() {
        File fileMain = new File(ConstPath.APP_PATH);
        if (!fileMain.exists()) {
            fileMain.mkdirs();
        }
        //新建一个File，传入文件夹目录
        File file = new File(ConstPath.DOWNLOAD_PATH);
        //判断文件夹是否存在，如果不存在就创建，否则不创建
        if (!file.exists()) {
            //通过file的mkdirs()方法创建
            file.mkdirs();
        }
    }

    public void markDownloadSoDir() {
        File fileMain = new File(ConstPath.APP_PATH);
        if (!fileMain.exists()) {
            fileMain.mkdirs();
        }
        //新建一个File，传入文件夹目录
        File file = new File(ConstPath.DOWNLOAD_PATH);
        //判断文件夹是否存在，如果不存在就创建，否则不创建
        if (!file.exists()) {
            //通过file的mkdirs()方法创建
            file.mkdirs();
        }
    }

    private String getIP(Context context) {
        String ip;
        if (SharepreferenceUtil.getCommUsbEnable(context)) {
            ip = SharepreferenceUtil.getCommIpUSB(context);
        } else {
            ip = SharepreferenceUtil.getCommIp(context);
        }
        return ip;
    }

    private int getPort(Context context) {
        String port;
        if (SharepreferenceUtil.getCommUsbEnable(context)) {
            port = SharepreferenceUtil.getCommPortUSB(context);
        } else {
            port = SharepreferenceUtil.getCommPort(context);
        }
        return Integer.parseInt(port);
    }

    private String getYESAM(Context context) {
        String yEsamNum = ZoomSPUtils.getYesamNum();
        return yEsamNum;
    }

    private String getUri(String methodName) {
        return COMMON_URI_PRE + methodName;
    }


    /**
     * post请求数据
     *
     * @param context       上下文
     * @param methodName    方法名称
     * @param requestParams 请求参数 json格式
     */
    public void postDataCallback(final Context context,
                                 String methodName, String requestParams, final IHttpCallbackInterface listener) throws RemoteException {

        if (!SharepreferenceUtil.getCommUsbEnable(context) && !NetWorkUtil.getInstance().isConnected(context)) {
            listener.onFailed(HTTP_REQUEST_NO_NET_WORK, HTTP_NET_NETWORK);
            return;
        }

        String ip = getIP(context);
        int port = getPort(context);
        String yesam = getYESAM(context);
        String uri = getUri(methodName);
        String seq = getSeq();


        com.hzwq.codec.client.model.BaseRequestParams params = new com.hzwq.codec.client.model.BaseRequestParams();

        JSONObject jb = null;

        try {
            jb = new JSONObject(requestParams);
            Iterator iterator = jb.keys();
            while (iterator.hasNext()) {
                String key = iterator.next() + "";
                params.put(key, jb.get(key).toString());

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //   HttpClientUtil2.
        HttpClientUtil2.post(ip, port, uri, yesam, seq, params, new IDataCallback() {
            @Override
            public void onFailure(String error) {
                LogUtil.e("请求失败：errorMsg == " + error);

                try {
                    listener.onFailed(HTTP_RESPONSE_CODE_FAIL, error);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onSuccess(String result) {
                LogUtil.e("请求成功：response == " + result);
                //2020/5/11添加判断返回值为8，重新登录。
                try {
                    //校验token 和uid是否失效
                    BaseEntity baseEntity = JsonUtil.parseJsonToBean(result, BaseEntity.class);
                    if (baseEntity == null || TextUtils.isEmpty(baseEntity.getRT_F())) {
                        listener.onFailed(0, "返回数据格式有误");
                        return;
                    }
                    if ("8".equals(baseEntity.getRT_F())) {
                        listener.onFailed(0, baseEntity.getRT_D());
                        reLogin(context);

                    } else {
                        listener.onSuccess(result);
                    }

                } catch (RemoteException e) {
                    e.printStackTrace();
                    try {
                        listener.onFailed(0, e.getMessage());
                    } catch (RemoteException e1) {
                        e1.printStackTrace();
                    }
                }

            }
        });

    }


    /**
     * multipart方式上传文件
     *
     * @param context           上下文
     * @param methodName        方法名
     * @param param             参数字符串
     * @param filePaths         多个文件地址字符串，用;隔开
     * @param callbackInterface 回调接口
     */
    public void uploadFile(Context context, String methodName, String param, String filePaths, String fileKey, final BaseOperateRouter.CompleteListener callbackInterface) {

        //检查数据
        if (TextUtils.isEmpty(filePaths)) {

            callbackInterface.complete(HTTP_RESPONSE_CODE_FAIL, "上传文件路径为空");

            return;
        }

        String ip = getIP(context);
        int port = getPort(context);
        String yesam = getYESAM(context);
        String uri = getUri(methodName);
        String seq = getSeq();

        String requestParms = param + UID_E + ZoomSPUtils.getUid() + MAC_E + ZoomSPUtils.getMac();

        com.hzwq.codec.client.model.BaseRequestParams params = new com.hzwq.codec.client.model.BaseRequestParams();
        params.put(SERVER_NAME, UPFILESERVER);
        params.put(REQUEST_PARM, DataConversionUtil.str2HexStr(requestParms));
        if (!TextUtils.isEmpty(filePaths)) {
            String[] files = filePaths.split(";");
            List<File> fileList = new ArrayList<>();
            for (String path : files) {
                fileList.add(new File(path));
            }

            if (fileList.size() > 0) {
                for (File item : fileList) {
                    LogUtil.d(TAG_UPFILE, " name=" + item.getName());
                    try {
                        params.put("file", item);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        params.setRequestMethod(RequestMethod.MULTIPARTPOST);

        HttpClientUtil2.post(ip, port, uri, yesam, seq, params, new IDataCallback() {
            @Override
            public void onFailure(String error) {
                LogUtil.e("请求失败：errorMsg == " + error);

                callbackInterface.complete(HTTP_RESPONSE_CODE_FAIL, error);

            }

            @Override
            public void onSuccess(String result) {
                LogUtil.e("cj100", "请求成功：response == " + result);
                try {
                    JSONObject jb = new JSONObject(result);
                    String RT_F = jb.optString("RT_F");
                    //返回错误时
                    if (TextUtils.isEmpty(RT_F) || !RT_F.equals("1")) {
                        callbackInterface.complete(HTTP_RESPONSE_CODE_FAIL, TextUtils.isEmpty(jb.optString("RT_D")) ? HTTP_UPLOAD_FILE_FAIL : jb.optString("RT_D"));
                    } else {
                        callbackInterface.complete(HTTP_RESPONSE_CODE_SUCCESS, result);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        });


    }

    /**
     * 参数查询接口
     *
     * @param context
     * @param appIdentity       应用标识(APP包名或其它标识)
     * @param paramVersion      参数版本号
     * @param callbackInterface 请求数据的回调
     */
    public void commParmUpdate(Context context, String appIdentity, String paramVersion, IHttpCallbackInterface callbackInterface) {
        LogUtil.d("参数查询：" + appIdentity + ", version : " + paramVersion);

        StringBuilder sb = new StringBuilder();
        sb.append("commParmUpdate.do?");//方法名+?
        if (!TextUtils.isEmpty(appIdentity)) {
            sb.append("&appIdentity=");
            sb.append(appIdentity);

        }
        if (!TextUtils.isEmpty(paramVersion)) {
            sb.append("&paramVersion=");
            sb.append(paramVersion);
        }

        JSONObject jb = new JSONObject();
        try {
            String paramsHex = DataConversionUtil.str2HexStr(sb.toString());
            jb.put("SERVER_NAME", "auth-service");
            jb.put("REQUEST_PARM", paramsHex);
            jb.put("UID", SharepreferenceUtil.getUid(context));
            jb.put("MAC", "12345");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            postDataCallback(context, "commFront.do", jb.toString(), callbackInterface);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    private void postRequest(final Context context, String methodName, final String header, String requestParams, final IHttpCallbackInterface linstener) throws RemoteException {
        if (!SharepreferenceUtil.getCommUsbEnable(context) && !NetWorkUtil.getInstance().isConnected(context)) {
            //无网络时进入主界面
            linstener.onFailed(HTTP_REQUEST_NO_NET_WORK, HTTP_NET_NETWORK);
            return;
        }

        if (SharepreferenceUtil.getCommUsbEnable(context)) {
            OkHttpManager.getClient(context).dispatcher().setMaxRequests(1);
            OkHttpManager.getClient(context).dispatcher().setMaxRequestsPerHost(1);
        } else {
            //最大允许并发请求任务
            OkHttpManager.getClient(context).dispatcher().setMaxRequests(20);
            //最大允许同一host的请求任务个数
            OkHttpManager.getClient(context).dispatcher().setMaxRequestsPerHost(5);
        }

        String url = getUrl(context) + methodName;
        LogUtil.d(TAG_POST, "url=" + url + "====" + methodName);
        boolean b = InputCheckUtil.checkInput(url, InputCheckUtil.checkUrl);
        if (!b) {
            linstener.onFailed(HTTP_RESPONSE_CODE_FAIL, URL_WRONG);
            return;
        }

        BaseRequestParams params = new BaseRequestParams();

        JSONObject jb = null;

        StringBuilder sb = new StringBuilder();
        try {
            jb = new JSONObject(requestParams);
            Iterator iterator = jb.keys();
            while (iterator.hasNext()) {
                String key = iterator.next() + "";
                params.put(key, jb.get(key).toString());
                sb.append(key);
                sb.append(jb.get(key).toString());

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LogUtil.d(TAG_POST, url);
        LogUtil.d(TAG_POST, TEXT_REQUEST_PARAM + jb.toString());
        LogUtil.d(TAG_POST, TEXT_REQUEST_PARAM + params.toString());
        LogUtil.d(TAG_POST, "REQUEST_PARM: " + DataConversionUtil.hexStr2Str(params.urlParams.get("REQUEST_PARM")));
        LogUtil.d(TAG_POST, TEXT_REQUEST_PARAM + sb.toString());
        //   HttpClientUtil.
        HttpClientUtil.post(context, url, header, params,
                new OkHttpManager.Listener<String>() {
                    @Override
                    public void onResponse(final String response) {
                        LogUtil.d(WEB_SUCCESS, response);
                        try {
                            //校验token 和uid是否失效
                            BaseEntity baseEntity = JsonUtil.parseJsonToBean(response, BaseEntity.class);
                            if (baseEntity == null || TextUtils.isEmpty(baseEntity.getRT_F())) {
                                linstener.onFailed(0, "返回数据格式有误");
                                return;
                            }
                            if ("8".equals(baseEntity.getRT_F())) {
                                linstener.onFailed(0, baseEntity.getRT_D());
                                reLogin(context);

                            } else {
                                linstener.onSuccess(response);
                            }

                        } catch (RemoteException e) {
                            e.printStackTrace();
                            try {
                                linstener.onFailed(0, e.getMessage());
                            } catch (RemoteException e1) {
                                e1.printStackTrace();
                            }
                        }

                    }
                }, new OkHttpManager.ErrorListener() {
                    @Override
                    public void onErrorResponse(OkHttpManager.OkHttpError error) {

                        LogUtil.d(WEB_FAILED, error.getLocalizedMessage());
                        try {
                            //校验token 和uid是否失效
                            BaseEntity baseEntity = JsonUtil.parseJsonToBean(error.getLocalizedMessage(), BaseEntity.class);
                            if (baseEntity == null || TextUtils.isEmpty(baseEntity.getRT_F())) {
                                linstener.onFailed(HTTP_RESPONSE_CODE_FAIL, error.getLocalizedMessage());
                                return;
                            }
                            if ("8".equals(baseEntity.getRT_F())) {
                                linstener.onFailed(HTTP_RESPONSE_CODE_FAIL, baseEntity.getRT_D());
                                reLogin(context);
                                return;
                            }
                            linstener.onFailed(HTTP_RESPONSE_CODE_FAIL, error.getLocalizedMessage());
                            //保存错误日志
                            ErrorLogUtil.getInstance().saveException(error.getLocalizedMessage(), ErrorLogUtil.TYPE_WORK);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public void getKnows(final Context context, String methodName, final String header, String requestParams, final IHttpCallbackInterface linstener) throws RemoteException {
        if (!SharepreferenceUtil.getCommUsbEnable(context) && !NetWorkUtil.getInstance().isConnected(context)) {
            //无网络时进入主界面
            linstener.onFailed(HTTP_REQUEST_NO_NET_WORK, HTTP_NET_NETWORK);
            return;
        }

        if (SharepreferenceUtil.getCommUsbEnable(context)) {
            OkHttpManager.getClient(context).dispatcher().setMaxRequests(1);
            OkHttpManager.getClient(context).dispatcher().setMaxRequestsPerHost(1);
        } else {
            //最大允许并发请求任务
            OkHttpManager.getClient(context).dispatcher().setMaxRequests(20);
            //最大允许同一host的请求任务个数
            OkHttpManager.getClient(context).dispatcher().setMaxRequestsPerHost(5);
        }

        String url = getUrl(context) + methodName;
        LogUtil.d(TAG_POST, "url=" + url + "====" + methodName);
        boolean b = InputCheckUtil.checkInput(url, InputCheckUtil.checkUrl);
        if (!b) {
            linstener.onFailed(HTTP_RESPONSE_CODE_FAIL, URL_WRONG);
            return;
        }

        BaseRequestParams params = new BaseRequestParams();

        JSONObject jb = null;

        StringBuilder sb = new StringBuilder();
        try {
            jb = new JSONObject(requestParams);
            Iterator iterator = jb.keys();
            while (iterator.hasNext()) {
                String key = iterator.next() + "";
                params.put(key, jb.get(key).toString());
                sb.append(key);
                sb.append(jb.get(key).toString());

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LogUtil.d(TAG_POST, url);
        LogUtil.d(TAG_POST, TEXT_REQUEST_PARAM + jb.toString());
        LogUtil.d(TAG_POST, TEXT_REQUEST_PARAM + params.toString());
        LogUtil.d(TAG_POST, "REQUEST_PARM: " + DataConversionUtil.hexStr2Str(params.urlParams.get("REQUEST_PARM")));
        LogUtil.d(TAG_POST, TEXT_REQUEST_PARAM + sb.toString());
        //   HttpClientUtil.
        HttpClientUtil.post(context, url, header, params,
                new OkHttpManager.Listener<String>() {
                    @Override
                    public void onResponse(final String response) {
                        try {
                            linstener.onSuccess(response);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }, new OkHttpManager.ErrorListener() {
                    @Override
                    public void onErrorResponse(OkHttpManager.OkHttpError error) {

                        LogUtil.d(WEB_FAILED, error.getLocalizedMessage());
                        try {
                            //校验token 和uid是否失效
                            BaseEntity baseEntity = JsonUtil.parseJsonToBean(error.getLocalizedMessage(), BaseEntity.class);
                            if (baseEntity == null || TextUtils.isEmpty(baseEntity.getRT_F())) {
                                linstener.onFailed(HTTP_RESPONSE_CODE_FAIL, error.getLocalizedMessage());
                                return;
                            }
                            if ("8".equals(baseEntity.getRT_F())) {
                                linstener.onFailed(HTTP_RESPONSE_CODE_FAIL, baseEntity.getRT_D());
                                reLogin(context);
                                return;
                            }
                            linstener.onFailed(HTTP_RESPONSE_CODE_FAIL, error.getLocalizedMessage());
                            //保存错误日志
                            ErrorLogUtil.getInstance().saveException(error.getLocalizedMessage(), ErrorLogUtil.TYPE_WORK);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void reLogin(Context context) {
        Intent intent = new Intent();
        //设置广播的名字（设置Action）
        intent.setAction("reLogin");
        //发送广播（无序广播）
        context.sendBroadcast(intent);
    }

    public void cancelBlockUpload(String filePath, String savePath, IHttpCallbackInterface httpCallbackInterface) {
        StringBuilder sb = new StringBuilder();
        sb.append("uploadCancel?");
        sb.append("fileName=");
        sb.append(new File(filePath).getName());
        sb.append("&UID=");//参数
        sb.append(SharepreferenceUtil.getUid(ZoomApplication.getInstance()));
        sb.append("&MAC=");
        sb.append("12345");
        if (!TextUtils.isEmpty(savePath)) {
            sb.append("&filePath=");
            sb.append(savePath);

        }

        JSONObject jb = new JSONObject();
        try {
            String paramsHex = DataConversionUtil.str2HexStr(sb.toString());
            jb.put("SERVER_NAME", "upfileserver");
            jb.put("REQUEST_PARM", paramsHex);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            postRequest(ZoomApplication.getInstance(), "reqHttpFileUp.do", "", jb.toString(), httpCallbackInterface);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    /**
     * 分块上传中间层方法
     * 将返回值转complete参数
     */
    public void blockUploadFile(final String filePath, final String savePath, final boolean isDelete, final BaseOperateRouter.CompleteListener completeListener) {

        String fileUploadSize = SharepreferenceUtil.getFileUploadSize(ZoomApplication.getInstance());
        final long blockSize = TextUtils.isEmpty(fileUploadSize) ? 256 * 1024L : Long.parseLong(fileUploadSize) * 1024L;

        //校验文件
        File file = new File(filePath);
        if (!file.exists()) {
            completeListener.complete(0, new Gson().toJson(new ErrorMsg("文件不存在")));
            return;
        }

        //校验文件夹名称
        final String name = file.getName();
        if (file.isDirectory()) {
            if (!UUIDUtil.isValidUUID(name)) {
                completeListener.complete(0, new Gson().toJson(new ErrorMsg("文件夹名称需要为UUID")));
                return;
            }
        }

        if (!checkUploadFileSize(filePath)) {
            completeListener.complete(0, new Gson().toJson(new ErrorMsg("上传文件大小超限" + (UPLOAD_SIZE_LIMIT / 1024) + "K")));
            return;
        }

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                File zipPath = new File(ConstPath.BLOCK_UPLOAD_ZIP_PATH);
                if (!zipPath.exists()) {
                    FileUtils.createOrExistsDir(zipPath);
                }
                final String destPath = ConstPath.BLOCK_UPLOAD_ZIP_PATH + name + ".zip";
                try {
                    if (new File(destPath).exists()) {

                        completeListener.complete(2, new Gson().toJson(new BlockUploadProgress(0, 0, 3)));

                    } else {
                        completeListener.complete(2, new Gson().toJson(new BlockUploadProgress(0, 0, 1)));


                        ZipUtil.compress(filePath, destPath);

                        completeListener.complete(2, new Gson().toJson(new BlockUploadProgress(0, 0, 3)));

                    }

                    UploadManager.getInstance().upload(destPath, savePath, blockSize, filePath, isDelete, new UploadListener() {
                        @Override
                        public void result(boolean isSuccess, String msg) {
                            completeListener.complete(isSuccess ? 1 : 0, msg);

                        }

                        @Override
                        public void progress(int current, int total, int status) {

                            BlockUploadProgress blockUploadProgress = new BlockUploadProgress(current, total, status);
                            completeListener.complete(2, new Gson().toJson(blockUploadProgress));

                        }


                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        FixedThreadUtil.executeThread(runnable);

    }

    /**
     *
     */
    public void cancelBlockUploadFile(String filePath, String savePath, final BaseOperateRouter.CompleteListener completeListener) {

        UploadManager.getInstance().cancelUpload(filePath, savePath, new IHttpCallbackInterface.Stub() {
            @Override
            public void onSuccess(String result) throws RemoteException {
                completeListener.complete(1, result);

            }

            @Override
            public void onFailed(int errorCode, String errorMsg) throws RemoteException {

                completeListener.complete(0, errorMsg);
            }
        });
    }

    /**
     * 检查文件后缀名是否符合要求
     * return 0：正常满足
     * return 1：未配置文件上传类型
     * return 2：上传类型不在参数配置范围内
     */
    public int checkUploadFileType(String filePath) {
        String wfFileUploadType = com.sgcc.pda.sdk.utils.db.SharepreferenceUtil.getWFFileUploadType(ZoomApplication.getInstance());
        if (TextUtils.isEmpty(wfFileUploadType)) return 1;
        String[] split = wfFileUploadType.split(",");
        for (int i = 0; i < split.length; i++) {
            if (filePath.endsWith(split[i])) {
                return 0;
            }
        }
        return 2;
    }


    /**
     * 检查文件大小是否符合
     */
    private boolean checkUploadFileSize(String filePath) {
        File file = new File(filePath);
        long length = getTotalSizeOfDirectory(file);
        String wfFileUploadSize = com.sgcc.pda.sdk.utils.db.SharepreferenceUtil.getWFFileUploadSize(ZoomApplication.getInstance());
        if (TextUtils.isEmpty(wfFileUploadSize)) {
            wfFileUploadSize = String.valueOf(5 * 1024L);
        }
        LogUtil.e("cj", "上传限制" + wfFileUploadSize + "K");
        long limitSize = Long.parseLong(wfFileUploadSize) * 1024L;
        UPLOAD_SIZE_LIMIT = limitSize;
        return length <= limitSize;
    }

    // 递归方式 计算文件的大小
    private long getTotalSizeOfDirectory(final File file) {
        if (file.isFile())
            return file.length();
        final File[] children = file.listFiles();
        long total = 0;
        if (children != null)
            for (final File child : children)
                total += getTotalSizeOfDirectory(child);
        return total;
    }


    /**
     * 下载文件
     *
     * @param filePath 文件路径
     * @param savePath 本地保存路径
     */
    public void downloadPicFile(Context context, final String filePath, final String savePath, final BaseOperateRouter.CompleteListener listener) {
        if (!SharepreferenceUtil.getCommUsbEnable(context) && !NetWorkUtil.getInstance().isConnected(context)) {
            if (listener != null) {
                listener.complete(0, HTTP_NET_NETWORK);
            }
            return;
        }
        String url = getUrl(context)
                + "reqHttpFileDown.do?"
                + "SERVER_NAME=upfileserver"
                + "&UID=" + SharepreferenceUtil.getUid(context)
                + "&MAC=" + SharepreferenceUtil.getMac(context);

        LogUtil.d("downloadPicFile", url);
        LogUtil.e("downloadPicFile", savePath);

        try {
            File file = new File(savePath);
            if (!file.exists()) {// 创建新文件
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        FileWget fileWget = new FileWget(context, url, filePath, savePath);
        fileWget.start(new FileWget.IDownloadProgress() {
            @Override
            public void downloadProgress(int percent, String message) {
                if (listener != null) {


                    switch (percent) {
                        case FileWget.STATUS_START:
                            // 开始下载
                            break;
                        case FileWget.STATUS_STOP:
                            // 停止下载
                            break;
                        case FileWget.STATUS_FAIL:
                            listener.complete(0, message);
                            break;
                        case FileWget.STATUS_FINISH:
                            listener.complete(1, message);
                            break;
                        default:
                            JSONObject json = new JSONObject();
                            try {
                                json.put("percent", percent);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            listener.complete(2, json.toString());
                            break;
                    }

                }
            }
        });

    }


    /**
     * 获取seq,两个字节
     */
    private String getSeq() {
        int businessIdInt = RandomUtils.nextInt(65535);
        String seq = StringUtils.leftPad(ByteTools.int2HexStr(businessIdInt), 4, '0');
        return seq;
    }

}
